//*********************************************************
//
//    Copyright (c) Microsoft. All rights reserved.
//    This code is licensed under the Apache License, Version 2.0.
//    THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
//    ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
//    IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
//    PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************

namespace Microsoft.Research.eResearch.Common.Threading
{
    using System;
    using System.Threading;

    /// <summary>
    /// Wrapper class for executing action objects inside the thread.
    /// </summary>
    public class DelegateMarshaler
    {
        /// <summary>
        /// Instance of the synchronization context.
        /// </summary>
        private SynchronizationContext synchronizationContext = null;

        /// <summary>
        /// Initializes a new instance of the DelegateMarshaler class.
        /// </summary>
        /// <param name="synchronizationContext">Instance of current synchronization context.</param>
        private DelegateMarshaler(SynchronizationContext synchronizationContext)
        {
            this.synchronizationContext = synchronizationContext;
        }

        /// <summary>
        /// Gets a value indicating whether marshal required.
        /// </summary>
        private bool IsMarshalRequired
        {
            get
            {
                return synchronizationContext != SynchronizationContext.Current;
            }
        }

        /// <summary>
        /// Creates a wrapper for the current synchronization context.
        /// </summary>
        /// <returns>Instance of the <typeparamref name="DelegateMarshaler"/>.</returns>
        public static DelegateMarshaler Create()
        {
            if (SynchronizationContext.Current == null)
            {
                throw new InvalidOperationException("No SynchronizationContext exists for the current thread.");
            }

            return new DelegateMarshaler(SynchronizationContext.Current);
        }

        /// <summary>
        /// Invokes the <paramref name="action"/> object inside the thread.
        /// </summary>
        /// <param name="action">Instance of the Action class.</param>
        public void Invoke(Action action)
        {
            if (!this.IsMarshalRequired)
            {
                action();
            }
            else
            {
                synchronizationContext.Send(o => action(), null);
            }
        }     
    }
}
